﻿using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;

using System.Text;
using System.Text.RegularExpressions;

namespace Coldairarrow.Business
{
    public class TenantProvider : ITenantProvider, IScopedDependency
    {
        private IOperator _operator;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public TenantProvider(IHttpContextAccessor httpContextAccessor, IOperator @operator)
        {
            _httpContextAccessor = httpContextAccessor;
            _operator = @operator;
        }

        /// <summary>
        /// 取得部门Id
        /// </summary>
        /// <returns></returns>
        public string GetDepartmentId()
        {
           
            return GetTenantIdByUserToken();
        }

        /// <summary>
        /// 根据用户token取得用户所在部门Id
        /// </summary>
        /// <returns></returns>
        public string GetTenantIdByUserToken()
        {
            HttpRequest req = _httpContextAccessor?.HttpContext?.Request;
            if (req == null)
            {
                return string.Empty;
            }
            string token = GetToken(req);
            if (string.IsNullOrEmpty(token))
            {
                return string.Empty;
            }

            var payload = JWTHelper.GetPayload<JWTPayload>(token);
            if (payload == null)
            {
                return string.Empty;
            }
            return payload.FactoryId;
        }
        /// <summary>
        /// 取得用户Token，如果用户没登陆，返回空字符串，避免异常
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        private string GetToken(HttpRequest req)
        {
            string tokenHeader = req.Headers["Authorization"].ToString();
            if (tokenHeader.IsNullOrEmpty())
                return null;

            string pattern = "^Bearer (.*?)$";
            if (!Regex.IsMatch(tokenHeader, pattern))
            {
               // throw new Exception("token格式不对!格式为:Bearer {token}");
                return null;
            } 
            string token = Regex.Match(tokenHeader, pattern).Groups[1]?.ToString();
            return token;
        }
    }
}
